﻿using Algorithm.Check;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Algorithm.Check.ExtensionForCRC16;

namespace NewDevice.RS485
{
    public class PWM_Y30
    {
        private readonly OldSerialBase _serial;
        private readonly int _slaveId;
        private readonly string _deviceName;
        private readonly ChannelHexConverter hexConverter;

        public PWM_Y30(OldSerialBase bus, int slaveId, string name = "PWM方波输出模块")
        {
            _serial = bus;
            this._slaveId = slaveId;
            this._deviceName = name;
            hexConverter = new ChannelHexConverter();
        }

        /// <summary>
        /// 设置默认频率，单位HZ
        /// </summary>
        public void SetDeFaultFreunency(int value)
        {
            byte[] bytes = ConvertToCustomBytes(value);

            byte[] data = [
                (byte)_slaveId,
                0x10,0x00,0x22,0x00,0X02,0X04
            ];
            byte[] mergedArray = data.Concat(bytes).ToArray();
            byte[] cmd = mergedArray.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            var recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
        }

        /// <summary>
        /// 读取默认频率，单位HZ
        /// </summary>
        public int GetDeFaultFreunency()
        {
            byte[] data = [
                   (byte)_slaveId,
                0x3,0x00,0x22,0x00,0X02
               ];
            byte[] cmd = data.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            byte[] recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
            byte[] vv = new byte[4];
            Array.Copy(recv, 3, vv, 0, 4);
            // 方法2：使用 BitConverter（需反转字节序）
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(vv); // 反转为大端序
            }
            int value = BitConverter.ToInt32(vv, 0);
            return value;
        }

        /// <summary>
        /// 设置单工位输出占空比，使用默认赫兹
        /// </summary>
        public void SetOneStation(int index, int value)
        {
            byte[] stationByte = ChannelHexConverter.GetBytesForChannel4(index);
            byte[] bytes = BitConverter.GetBytes((ushort)value); // 转成2字节（ushort）
            if (BitConverter.IsLittleEndian) // 检查字节序（小端序需反转）
            {
                Array.Reverse(bytes);
            }
            byte[] data = [
                (byte)_slaveId,
                0x06
            ];
            byte[] mergedArray = data.Concat(stationByte).ToArray();
            byte[] mergedArray2 = mergedArray.Concat(bytes).ToArray();
            byte[] cmd = mergedArray2.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            var recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
        }

        /// <summary>
        /// 设置全工位输出状态以及占空比，使用默认赫兹
        /// </summary>
        public void SetALLStation(int value)
        {
            byte[] data = [
               (byte)_slaveId,
                0x10,0x05,0xDC,0x00,0X20,0X40,0xFF,0xFF,0xFF,0xFF
           ];
            byte[] mergedArray = data;
            for (int i = 0; i < 30; i++)
            {
                byte[] bytes = BitConverter.GetBytes((ushort)value); // 转成2字节（ushort）
                if (BitConverter.IsLittleEndian) // 检查字节序（小端序需反转）
                {
                    Array.Reverse(bytes);
                }
                mergedArray = mergedArray.Concat(bytes).ToArray();
            }

            byte[] cmd = mergedArray.WithCRC16(CRC16Type.Modbus).ToArray();
            _serial.deviceName = _deviceName;
            var recv = _serial.SendBytesAndWaitResponse(cmd, ReceivedDataCheck.FuncModbusCRC16Check);
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            _serial.Close();
        }

        /// <summary>
        /// 字节转化
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private byte[] ConvertToCustomBytes(int value)
        {
            byte[] bytes = new byte[4];
            bytes[0] = (byte)(value >> 24); // 第 4 字节 (00)
            bytes[1] = (byte)(value >> 16);  // 第 3 字节 (00)
            bytes[2] = (byte)(value >> 8);  // 第 2 字节 (02)
            bytes[3] = (byte)(value & 0xFF); // 第 1 字节 (52)

            //bytes[0] = (byte)(value >> 8); // 第 4 字节 (00)
            //bytes[1] = (byte)(value & 0xFF); // 第 3 字节 (00)
            //bytes[2] = (byte)(value >> 24);  // 第 2 字节 (02)
            //bytes[3] = (byte)(value >> 16); // 第 1 字节 (52)
            return bytes;
        }
    }

    //public class ChannelHexConverter
    //{
    //    // 存储通道号与对应字节数组的字典
    //    private static Dictionary<int, byte[]> _channelToHexMap;

    //    public ChannelHexConverter()
    //    {
    //        _channelToHexMap = new Dictionary<int, byte[]>();

    //        // 初始化30个通道的映射（通道0~29）
    //        for (int channel = 0; channel < 30; channel++)
    //        {
    //            // 计算当前通道的十六进制值（05 DE + channel）
    //            ushort hexValue = (ushort)(0x05DE + channel);

    //            // 将ushort转换为2字节数组（大端序）
    //            byte[] bytes = new byte[]
    //            {
    //            (byte)(hexValue >> 8),  // 高位字节（如0x05）
    //            (byte)(hexValue & 0xFF) // 低位字节（如0xDE）
    //            };

    //            _channelToHexMap.Add(channel, bytes);
    //        }
    //    }

    //    // 根据通道号获取对应的字节数组
    //    public static byte[] GetBytesForChannel(int channel)
    //    {
    //        if (_channelToHexMap.TryGetValue(channel, out byte[] bytes))
    //        {
    //            return bytes;
    //        }
    //        throw new ArgumentException($"无效的通道号: {channel}，支持范围0~29");
    //    }
    //}
}